package logic

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"selection-inventory/application/applet/internal/svc"
)

const maxFileSize = 10 << 20 // 10MB

type UploadPictureLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadPictureLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadPictureLogic {
	return &UploadPictureLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadPictureLogic) UploadPicture(req *http.Request) (resp string, err error) {
	_ = req.ParseMultipartForm(maxFileSize)
	file, handler, err := req.FormFile("file")
	if err != nil {
		return "", err
	}
	defer file.Close()

	_, mErr := os.Stat("./static")
	if mErr != nil {
		mErr = os.Mkdir("./static", os.ModePerm)
		if mErr != nil {
			fmt.Println("文件夹创建失败", mErr)
			return
		}
	}

	savePath := "./static"
	objectKey := genFilename(handler.Filename)
	saveFilePath := filepath.Join(savePath, objectKey)
	// 创建一个新文件，用于保存上传的文件内容
	newFile, err := os.Create(saveFilePath)
	if err != nil {
		return
	}
	defer newFile.Close()

	// 将上传的文件内容复制到新文件中
	_, err = io.Copy(newFile, file)
	if err != nil {
		return
	}
	fmt.Println(savePath)
	return genFileURL(objectKey), nil
}

func genFilename(filename string) string {
	return fmt.Sprintf("%d_%s", time.Now().UnixMilli(), filename)
}

func genFileURL(objectKey string) string {
	return fmt.Sprintf("/static/%s", objectKey)
}
